package top.maof.book.service.myImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.maof.book.dao.PermMapper;
import top.maof.book.model.Perm;
import top.maof.book.result.PageData;
import top.maof.book.result.PageWrap;
import top.maof.book.service.PermService;
import top.maof.book.utils.Utils;

@Service
public class PermServiceImpl extends ServiceImpl<PermMapper, Perm> implements PermService {
    @Autowired
    private PermMapper permMapper;

    @Override
    public PageData<Perm> findPage(PageWrap<Perm> pageWrap) {
        IPage<Perm> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        QueryWrapper<Perm> queryWrapper = new QueryWrapper<>();
        Utils.MP.blankToNull(pageWrap.getModel());
        if (pageWrap.getModel().getId() != null) {
            queryWrapper.lambda().eq(Perm::getId, pageWrap.getModel().getId());
        }
        if (pageWrap.getModel().getPermission() != null) {
            queryWrapper.lambda().eq(Perm::getPermission, pageWrap.getModel().getPermission());
        }
        if (pageWrap.getModel().getDesc() != null) {
            queryWrapper.lambda().eq(Perm::getDesc, pageWrap.getModel().getDesc());
        }
        for (PageWrap.SortData sortData : pageWrap.getSorts()) {
            if (sortData.getDirection().equalsIgnoreCase(PageWrap.DESC)) {
                queryWrapper.orderByDesc(sortData.getProperty());
            } else {
                queryWrapper.orderByAsc(sortData.getProperty());
            }
        }
        return PageData.from(permMapper.selectPage(page, queryWrapper));
    }

    @Override
    public int add(Perm perm) {
        return permMapper.insert(perm);
    }

    @Override
    public Perm find(int id) {
        return permMapper.selectByPrimaryKey(id);
    }

    @Override
    public int update(Perm perm) {
        return permMapper.updateByPrimaryKeySelective(perm);
    }

    @Override
    public int delete(int id) {
        return permMapper.deleteByPrimaryKey(id);
    }
}
